#' @TODO 利用maf文件，突变分析 v1.0（目前先这么用着，后面可以用table或者其他来进行改进）
#' @title SNV突变分析 
#' 
#' @param maf_file_dir  maf文件所在地址，字符串形式，直接给maf文件格式的df变量也可以
#'  
#' @param gene_list 兴趣基因list，字符串向量
#' @param phenotype 表型文件，maf文件路径，表型文件中，需要有`sample`，`riskgroup`，`Age`，`Stage`，`Gender`等几列，且列名需要一致
#' 在表型文件中，各列表型内容需统一成二分类变量，以便进行注释。二分类变量名，需要和下面的注释一致，或者需要自己改。
#' @param doMutGeneStat 逻辑值，是否在分组间进行
#'  
#'@param return_file_style maf文件数据，生成本地图片
#'@param return_file 
#'
#'@Author *WYK*
maf_analize_v2 <- function(Clinical = NULL, Feature = NULL, maf_file_dir = NULL,
                           gene_list = NULL, topN = 20, output_dir = "./", 
                           Colored_OtherInfor = T,doMutGeneStat = F) {
  library(maftools)

  if (!dir.exists(output_dir)) {
    dir.create(output_dir, recursive = T)
  }

  if (!is.null(Feature)) {
    cli <- Clinical  %>%
      dplyr::rename(Tumor_Sample_Barcode = sample) %>% 
      select(any_of(c('Tumor_Sample_Barcode',Feature))) %>%# , age, stage, gender
      mutate(Tumor_Sample_Barcode = substr(Tumor_Sample_Barcode, 1, 12))
  } else {
    cli <- Clinical %>% # , age, stage, gender
      dplyr::rename(Tumor_Sample_Barcode = sample) %>%
      mutate(Tumor_Sample_Barcode = substr(Tumor_Sample_Barcode, 1, 12))
  }  

  # maf_file_dir <- luad_maf

  maf_data <- read.maf(
    maf = maf_file_dir,
    clinicalData = cli,
    isTCGA = T,
    verbose = T
  )

  # maf_data <- maf_all  
  vc_cols <- RColorBrewer::brewer.pal(n = 8, name = "Paired")
  names(vc_cols) <- c(
    "Frame_Shift_Del",
    "Missense_Mutation",
    "Nonsense_Mutation",
    "Multi_Hit",
    "Frame_Shift_Ins",
    "In_Frame_Ins",
    "Splice_Site",
    "In_Frame_Del"
  )

  Gene_mut_res <- maftools::getGeneSummary(x = maf_data) %>%
    as.data.frame() %>%
    arrange(desc(total))

  if (!is.null(gene_list)) {
    top_mut_gene <- Gene_mut_res %>%
      filter(Hugo_Symbol %in% gene_list) %>%
      arrange(desc(total)) %>%
      dplyr::select(Hugo_Symbol) %>%
      pull() %>%
      .[1:topN]

    pdf(file = sprintf("%s/Fiigure_SNV_top_genelist.pdf", output_dir), width = 7, height = 7.5)
    oncoplot(
      maf = maf_data,
      top = topN,
      fontSize = .8,
      draw_titv = T,
      legendFontSize = 1.5,
      # clinicalFeatures = c("Age", "Stage", "Gender"),
      colors = vc_cols,
      annotationFontSize = 1.2,
      # annotationColor = anno_col,
      anno_height = 2.6,
      genes = top_mut_gene,
      sortByAnnotation = F
    )
    dev.off()
  }


  if (isTRUE(Colored_OtherInfor)) {
    group_infor <- maf_data@clinical.data
    clinical_names <- setdiff(colnames(group_infor), "Tumor_Sample_Barcode")

    color_defined <- rep(RColorBrewer::brewer.pal(9, "Paired"), 10)
    # color_defined <- rep(RColorBrewer::brewer.pal(12,'Set3'),10)
    i <- 1
    color_in_maf <- lapply(clinical_names, function(x) {
      # x <- clinical_names[1]
      color_name <- group_infor %>%
        pull(x) %>%
        unique() %>%
        sort()

      color_used <- color_defined[i:(i + length(color_name) - 1)]
      names(color_used) <- color_name

      color_defined <- color_defined[-c(i:(i + length(color_name) - 1))]
      i <<- i + length(color_name)
      return(color_used)
    })

    names(color_in_maf) <- clinical_names

    if ("Score" %in% clinical_names) {
      anno_col1 <- c("#E41A1C", "#377EB8")
      names(anno_col1) <- c("High", "Low")
      color_in_maf[["Score"]] <- anno_col1
    }
  }


  pdf(file = sprintf("%s/SNV_HighLow.pdf", output_dir), width = 7, height = 7.5)
  oncoplot(
    maf = maf_data,
    top = topN,
    fontSize = .8,
    draw_titv = F,
    legendFontSize = 1.1,
    clinicalFeatures = names(color_in_maf),
    colors = vc_cols,
    annotationFontSize = 1,
    annotationColor = color_in_maf,
    anno_height = length(names(color_in_maf)) / 2,
    # genes = inf_gene$Symbol,
    sortByAnnotation = TRUE
  )
  dev.off()

  maf_data_high <- maf_data
  maf_data_low <- maf_data

  maf_data_high <- subsetMaf(maf_data, tsb = {
    maf_data@clinical.data %>%
      filter(Score == "High") %>%
      dplyr::select(Tumor_Sample_Barcode) %>%
      pull()
  })

  maf_data_low <- subsetMaf(maf_data, tsb = {
    maf_data@clinical.data %>%
      filter(Score == "Low") %>%
      dplyr::select(Tumor_Sample_Barcode) %>%
      pull()
  })

  pdf(file = sprintf("%s/Figure_SNV_High_group.pdf", output_dir), width = 6, height = 7)
  # pdf(file = sprintf("%sFigure_SNV_High_group_in_ER_pathway.pdf",output_dir), width = 6, height = 7)
  oncoplot(
    maf = maf_data_high,
    top = topN,
    fontSize = .8,
    draw_titv = F,
    legendFontSize = 1.1,
    clinicalFeatures = names(color_in_maf),
    colors = vc_cols,
    annotationFontSize = 1,
    annotationColor = color_in_maf,
    anno_height = length(names(color_in_maf)) / 2,
    # genes = top_mut_gene,
    sortByAnnotation = TRUE
  )
  dev.off()


  pdf(file = sprintf("%s/Figure_SNV_Low_group.pdf", output_dir), width = 6, height = 7)
  # pdf(file = sprintf("%sFigure_SNV_Low_group_in_ER_pathway.pdf",output_dir), width = 6, height = 7)
  oncoplot(
    maf = maf_data_low,
    top = topN,
    fontSize = .8,
    draw_titv = F,
    legendFontSize = 1.1,
    clinicalFeatures = names(color_in_maf),
    colors = vc_cols,
    annotationFontSize = 1,
    annotationColor = color_in_maf,
    anno_height = length(names(color_in_maf)) / 2,
    # genes = top_mut_gene,
    sortByAnnotation = TRUE
  )
  dev.off()

  # pdf(file = sprintf("%s/Figure_SNV_coOncoplot.pdf", output_dir), width = 6, height = 7)
  # coOncoplot(
  #   m1 = maf_data_low, m2 = maf_data_high, 
  #   m1Name = "Low", m2Name = "High",
  #   genes = top_mut_gene,
  #   clinicalFeatures1 = names(color_in_maf),
  #   clinicalFeatures2 = names(color_in_maf)
  # )
  # dev.off()

  if (isTRUE(doMutGeneStat)) {
    mut_matrix <- maftools::mutCountMatrix(maf_data) %>% as.data.frame()

    mut_matrix_long <- mut_matrix %>%
      tibble::rownames_to_column("gene") %>%
      tidyr::pivot_longer(cols = -gene, names_to = "sample", values_to = "mut") %>%
      dplyr::full_join(maf_data@clinical.data %>% select(Tumor_Sample_Barcode, 2) %>%
        rename(sample = Tumor_Sample_Barcode)) %>%
      mutate(mut = ifelse(mut > 0, "mut", "wt"))

    genelist <- unique(mut_matrix_long %>% pull(gene)) %>%
      na.omit() %>%
      as.character()

    count_df <- mut_matrix_long %>%
      select(-sample) %>%
      group_by(gene, mut, Score) %>%
      summarise(n = n()) %>%
      na.omit()

    library(furrr)

    plan(multisession, workers = 72)
    chisq.test.p <- furrr::future_map_dbl(genelist, function(x) {
      # x <- 'TTN'
      message(x)
      count_mix <- count_df %>%
        filter(gene == x) %>%
        pull(n) %>%
        matrix(., nrow = 2, ncol = 2)

      p <- chisq.test(count_mix, simulate.p.value = T, B = 2000) %>%
        .$p.val

      return(p)
    })


    # chisq.test.p <- map_dbl(genelist, function(x) {
    #   # x <- "ZNF789"
    #   message(x)
    #   mut_matrix_long %>%
    #     filter(gene == x) %>%
    #     select(mut, colnames(mut_matrix_long)[4]) %>%
    #     table() %>%
    #     chisq.test(., simulate.p.value = T) %>%
    #     .$p.val
    # })

    chisq.test_res <- tibble(gene = genelist, chisq.test.p = chisq.test.p) %>% arrange(chisq.test.p)
    write_tsv(x = chisq.test_res, file = sprintf("%s/chisq.test_res.txt", output_dir))
  }


  # tmb_1 <- tmb(maf = maf_data) %>%
  #   left_join(., maf_data@clinical.data %>% dplyr::select(Tumor_Sample_Barcode, Group))

  # p <- ggplot(tmb_1 %>% filter(total_perMB_log != "-Inf" & Group != "NA"), aes(Group, total_perMB_log)) +
  #   geom_boxplot(aes(group = Group, fill = Group), color = "black", alpha = 0.1, width = 0.4, notch = T) +
  #   geom_jitter(aes(colour = Group), position = position_jitter(0.12), alpha = 0.8) +
  #   geom_violin(aes(group = Group, fill = Group), color = "black", alpha = 0.1, width = 0.55) +
  #   ggpubr::stat_compare_means() +
  #   egg::theme_article(base_size = 14) +
  #   theme(legend.position = "none") +
  #   scale_fill_manual(values = c("High" = "#E41A1C", "Low" = "#377EB8")) +
  #   scale_color_manual(values = c("High" = "#E41A1C", "Low" = "#377EB8")) +
  #   labs(x = "Risk Group", y = "total perMB log")

  # ggsave(sprintf("%s/snv/High_low_box_p.pdf",output_dir), width = 4, height = 4)

  return(maf_data)
}
